package com.shiro.test.mvc.filter;

import com.shiro.test.mvc.pojo.User;
import com.shiro.test.mvc.service.IUserService;
import com.shiro.test.mvc.util.Constants;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * Created by Administrator on 2020/11/26 0026.
 */
public class MyShiroRealm extends AuthorizingRealm{

    @Autowired
    private IUserService userService;

    //每次访问时权限执行
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        User user = (User) session.getAttribute(Constants.SESSION_USER);
        List<Integer> roleIds = userService.getUserRoles(user.getId());
        if (roleIds != null && roleIds.size()>0){
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            for (Integer roleId : roleIds) {
                info.addRole(roleId.toString());
            }
            return info;
        }

        return null;
    }

    //登陆授权执行
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String email = (String) authenticationToken.getPrincipal();
        User user = userService.getUserByEmail(email);
        if(user != null){
            return new SimpleAuthenticationInfo(email,user.getPassword(),null,getName());
        }
        return null;
    }
}
